import React, { Component } from 'react';
import { StyleSheet, ScrollView, Image, Text, View, Dimensions, TouchableOpacity } from 'react-native';

let ScreenWidth = Dimensions.get('window').width;
let ScreenHeight = Dimensions.get('window').height;
// UI图设计基准大小
const uiWidthPx = 750;
function px2dp(uiElementPx) {
  if (ScreenWidth > ScreenHeight) {
    return (uiElementPx * ScreenHeight) / uiWidthPx;
  }
  return (uiElementPx * ScreenWidth) / uiWidthPx;
}

/**
 * @author kanglang
 * @description 轮播图组件
 * @createDate 2020/7/21
 * swiperStyle 轮播图的样式
 * pageNoStyle 页码的样式
 * showDot 是否显示换页点 默认不显示
 * showPageNo 是否显示页面 默认不显示
 * imageData [{icon: '', contentId:''}] 如有点击事件需要有contentId
 * mgWidth 如果轮播图没有占满屏幕，则需要这个参数作为轮播图的宽度，mgWidth = ScreenWidth - 边距值 *2
 * isAuto 是否自动轮播，true 是 false 否，默认 true
 */

export default class XmSwiper extends Component {
  constructor(props) {
    super(props);
    const myImages = this.props.imageData && this.props.imageData.length > 0 ? this.props.imageData : [];
    this.state = {
      currentPage: 0,
      imageData: myImages
    };
  }

  componentDidMount() {
    const { imageData } = this.state;
    const { isAuto = true } = this.props;
    // 图片大于一张时，启动定时器
    if (imageData.length > 1 && isAuto) {
      this._startTimer();
    }
  }

  componentWillUnmount() {
    // 如果存在this.timer，则使用clearTimeout清空
    this.timer && clearTimeout(this.timer);
  }

  render() {
    const { showDot = false, showPageNo = false, borderRadius, mgWidth, dotBoxStyle } = this.props;
    const { imageData } = this.state;
    return (
      <View style={[styles.continer, borderRadius]}>
        <ScrollView
          ref='scrollView'
          // 水平方向
          horizontal
          // 当值为true时显示滚动条
          showsHorizontalScrollIndicator={false}
          // 当值为true时，滚动条会停在滚动视图的尺寸的整数倍位置
          pagingEnabled
          // 滑动完一贞
          onMomentumScrollEnd={(e) => {
            this._onAnimationEnd(e);
          }}
          // 开始拖拽
          onScrollBeginDrag={() => {
            this._onScrollBeginDrag();
          }}
          // 结束拖拽
          onScrollEndDrag={() => {
            this._onScrollEndDrag();
          }}
          style={borderRadius}
        >
          {imageData.length > 0 && this._renderAllImage()}
        </ScrollView>
        {
          showDot && imageData.length > 1 &&
          <View
            style={[styles.pageViewStyle, { width: mgWidth || ScreenWidth }, dotBoxStyle]}
          >
            {this._renderAllIndicator()}
          </View>
        }
        {
          showPageNo && imageData.length > 1 && this._renderPageNo()
        }
      </View>
    );
  }

  _renderPageNo() {
    const { currentPage, imageData } = this.state;
    const { pageNoStyle, mgWidth } = this.props;
    return (
      <View style={[styles.pageNoWrap, { width: mgWidth || ScreenWidth }, ]}>
        <View style={styles.pageNoStyle}>
          <Text style={[
            styles.pageStyle,
            styles.currentPageNoSize,
            pageNoStyle]}
          >
            {currentPage + 1}
          </Text>
          <Text style={[
            styles.pageStyle,
            pageNoStyle]}
          >
            /
            {imageData.length}
          </Text>
        </View>
      </View>
    );
  }

  // 开始滑动
  _onScrollBeginDrag() {
    this.timer && clearTimeout(this.timer);
  }

  // 停止滑动
  _onScrollEndDrag() {
    this.timer && this._startTimer();
  }

  xmBtnImage(imgsItem) {
    this.props.clickImage && this.props.clickImage(imgsItem);
  }

  // 展示轮播图
  _renderAllImage() {
    const { imageData } = this.state;
    const { swiperStyle, mgWidth, borderRadius, resizeMode } = this.props;
    let allImage = [];
    let imgsArr = imageData;
    for (let i = 0; i < imgsArr.length; i++) {
      let imgsItem = imgsArr[i];
      allImage.push(
        <TouchableOpacity
          style={[swiperStyle, styles.imageStyle, borderRadius, { width: mgWidth || ScreenWidth }, ]}
          activeOpacity={1}
          onPress={() => this.xmBtnImage(imgsItem)}
        >
          <Image
            key={i}
            source={{ uri: imgsItem.icon ? imgsItem.icon : null }}
            style={[swiperStyle, styles.imageStyle, borderRadius, { width: mgWidth || ScreenWidth }, ]}
            resizeMode={resizeMode || 'stretch'}
          />
        </TouchableOpacity>
      );
    }
    return allImage;
  }

  // 手动滑动分页实现
  _onAnimationEnd(e) {
    const { mgWidth } = this.props;
    const offsetWidth = mgWidth || ScreenWidth;
    // 求出偏移量
    let offsetX = e.nativeEvent.contentOffset.x + 1;
    // 求出当前页数
    let pageIndex = Math.floor(offsetX / offsetWidth);
    // 更改状态机
    this.setState({ currentPage: pageIndex });
  }

  // 页面指针实现
  _renderAllIndicator() {
    const { imageData } = this.state;
    const { dotWrapStyle, defaultWrapStyle } = this.props;
    let indicatorArr = [];
    let dotStyle;
    let imgsArr = imageData;
    for (let i = 0; i < imgsArr.length; i++) {
      dotStyle = (i == this.state.currentPage) ? (dotWrapStyle || styles.dotWrap) : (defaultWrapStyle || { backgroundColor: 'rgba(255,255,255,0.3)' });
      indicatorArr.push(
        <View key={i} style={[styles.dotDefault, dotStyle]} />
      );
    }
    return indicatorArr;
  }

  // 通过定时器实现自动播放轮播图
  _startTimer() {
    const { duration = 1, mgWidth } = this.props;
    const { imageData } = this.state;
    let { scrollView } = this.refs;
    this.timer = setInterval(
      () => {
        let imageCount = imageData.length;
        // 设置圆点
        let animated = true;
        let activePage = 0;
        if (this.state.currentPage >= imageCount - 1) {
          activePage = 0;
          animated = false;
        } else {
          activePage = this.state.currentPage + 1;
        }
        // 更新状态
        this.setState({ currentPage: activePage });
        // 让scrollview 滚动起来
        let offsetX = activePage * (mgWidth || ScreenWidth);
        scrollView.scrollResponderScrollTo({ x: offsetX, y: 0, animated });
      },
      duration * 1000
    );
  }
}

const styles = StyleSheet.create({
  continer: {
    backgroundColor: 'transparent'
  },
  imageStyle: {
    height: '100%',
    width: ScreenWidth
  },
  pageViewStyle: {
    height: px2dp(25) * 2,
    width: '100%',
    position: 'absolute',
    bottom: px2dp(0) * 2,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  pageNoWrap: {
    width: ScreenWidth,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  pageNoStyle: {
    backgroundColor: 'rgba(52, 51, 50, .4)',
    position: 'absolute',
    paddingLeft: px2dp(8) * 2,
    paddingRight: px2dp(8) * 2,
    borderRadius: px2dp(2) * 2,
    bottom: px2dp(16) * 2,
    right: px2dp(16) * 2,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',

  },
  pageStyle: {
    fontSize: px2dp(11) * 2,
    color: '#ffffff'
  },
  currentPageNoSize: {
    fontSize: px2dp(13) * 2
  },
  dotWrap: {
    backgroundColor: '#BA914A',
    width: px2dp(6) * 2,
    height: px2dp(6) * 2
  },
  dotDefault: {
    height: px2dp(6) * 2,
    width: px2dp(6) * 2,
    margin: px2dp(3) * 2,
    borderRadius: px2dp(8) * 2
  }
});
